//申请详情页！！！
//主要逻辑在后端API
//显示包括 [基本信息， 额外信息， 审批信息， 执行信息， 操作信息]，根据后端给的数据来区别显示
import React, {Component} from 'react'
import {View, Image, Text, ScrollView, Dimensions, Alert, TouchableOpacity} from 'react-native'
import Loading from '../common/loading'
import styles from '../../configs/styles'
import Helper from '../../helpers'
import {I18n} from '../../configs/enumeration'
import {GetApplyInfoApi, UpdateApplyApi} from '../../configs/api'
import {Table, TableWrapper, Row, Rows, Col, Cols, Cell} from 'react-native-table-component';

class ApplyShow extends Component {
  static navigationOptions = ({navigation}) => {
    return {
      title: ''
    }
  }

  //初始化props和state
  constructor(props) {
    super(props);
    const params = props.navigation.state.params
    this.state = {
      apply_id: params.apply_id,
      loading: true,
      data: {}
    }
  }

  componentDidMount() {
    this.getData()
  }

  getData = () => {
    GetApplyInfoApi(this.state.apply_id).then((data) => {
      this.setState({
        data: data,
        loading: false,
      })
    }).catch(err=>{
      Alert.alert('没有找到数据！')
      this.props.navigation.goBack()
    })
  };


  _base_info = () => {
    const {apply} = this.state.data
    return (
      <View style={[styles.apply_base, {marginTop: 0}]}>
        <View style={styles.apply_base_block}>
          <View>
            <Image source={Helper.avatar(apply.full_avatar)} style={styles.avatar}/>
          </View>
          <View style={{flex: 1, alignItems: 'flex-start', paddingLeft: 10}}>
            <Text style={{fontSize: 16, fontWeight: 'bold'}}>{apply.applicant_name}</Text>
            <Text style={[{paddingTop: 5}, Helper.replyColor(apply.status_name)]}>{apply.status_name}</Text>
          </View>
        </View>
        {this._label_item(['申请编号', apply.id], 1)}
        {this._label_item(['申请时间', apply.created_at], 2)}
        <View style={{padding: 10}}>
          <View>
            <Text style={styles.apply_title_text}>申请理由</Text>
          </View>
          <View style={{paddingTop: 10, paddingBottom: 10}}>
            <Text style={styles.apply_info_text}>{apply.remark}</Text>
          </View>
        </View>

      </View>
    )
  };

  _label_item = (arr, key = 0) => {
    return (
      <View style={styles.apply_base_block} key={key}>
        <View>
          <Text style={styles.apply_title_text}>{arr[0]}</Text>
        </View>
        <View style={styles.apply_base_block_right}>
          <Text style={styles.apply_info_text}>{arr[1]}</Text>
        </View>
      </View>
    )
  };
  _table_info = () => {
    const {apply} = this.state.data,
      items = apply.items
    if (items && items.head != null) {
      let [head1, ...tableHead] = items.head
      let tableTitle = [],
        tableData = []

      items.content.forEach((arr) => {
        let [x1, ...others] = arr
        tableTitle.push(x1)
        tableData.push(others)
      })
      const widthArr = new Array(items.head.length).fill(100)
      // const screenWidth = Dimensions.get('window').width;
      // const tableWidth = screenWidth-20
      return (
        <View style={styles.apply_table}>
          <View style={{padding: 15}}>
            <Text>{apply.business_name}信息</Text>
          </View>
          <Table style={styles.table} borderStyle={{borderWidth: 0, borderColor: 'white'}}>
            {/* Left Wrapper */}
            <TableWrapper style={{width: 100}} borderStyle={{borderWidth: 0, borderColor: 'white'}}>
              <Cell data={head1} style={styles.head} textStyle={styles.headText}/>
              {
                tableTitle.map((title, i) => (
                  <Cell key={i} data={title} height={55} style={i % 2 && {backgroundColor: '#f4f4f4'}}
                        textStyle={styles.titleText}/>
                ))
              }
            </TableWrapper>

            {/* Right scrollview Wrapper */}
            <ScrollView horizontal={true}>
              {/* If parent element is not table element, you should add the type of borderstyle. */}
              <TableWrapper borderStyle={{borderWidth: 0, borderColor: 'white'}}>
                <Row data={tableHead} style={styles.head} textStyle={styles.headText} widthArr={widthArr}/>
                {
                  tableData.map((data, i) => (
                    <Row key={i} data={data} style={[styles.list, i % 2 && {backgroundColor: '#f4f4f4'}]}
                         widthArr={widthArr} textStyle={styles.listText}/>
                  ))
                }
              </TableWrapper>
            </ScrollView>
          </Table>
        </View>
      )
    } else if (items && items.content != null) {
      return (
        <View style={styles.apply_base}>
          {items.content.map((t, i) => this._label_item(t, i))}
          {this._related_apply(apply.related_apply)}
        </View>
      )
    } else {
      return null
    }
  };

  _audit_item = (item, key) => {
    return (
      <View key={key} style={{padding: 10}}>
        <View style={{flexDirection: 'row'}}>
          <View style={{flexDirection: 'row'}}>
            <Image source={Helper.avatar(item.avatar)} style={styles.avatar}/>
            <Text style={{marginTop: 15, marginLeft: 10}}>
              {item.auditor || item.title}
            </Text>
            <Text style={[Helper.replyColor(item.reply), {
              marginTop: 15,
              marginLeft: 10
            }]}>{item.reply}</Text>
          </View>
          <View style={{flex: 1, alignItems: 'flex-end', paddingRight: 10}}>
            <Text style={[styles.apply_info_text, {marginTop: 15}]}>{item.time}</Text>
          </View>
        </View>
        <View style={{marginTop: -5}}>
          <Text style={[{marginLeft: 50}, styles.apply_info_text]}>{item.remark}</Text>
        </View>
      </View>
    )
  };
  _execution_item = (item, key) => {
    return (
      <View style={{flexDirection: 'row', padding: 10}} key={key}>
        <View style={{flexDirection: 'row'}}>
          <Image source={Helper.avatar(item.avatar)} style={styles.avatar}/>
          <Text style={{marginTop: 15, marginLeft: 10}}>
            {item.executer}
          </Text>
          <Text style={[(item.status_name == '待确认' ? styles.text_danger : styles.text_blue), {
            marginTop: 15,
            marginLeft: 10
          }]}>{item.status_name}</Text>
        </View>
        <View style={{flex: 1, alignItems: 'flex-end', paddingRight: 10}}>
          <Text style={[styles.apply_info_text, {marginTop: 15}]}>{item.status_name == '已确认' && item.time}</Text>
        </View>
      </View>
    )
  };

  _related_apply = (related_apply) => {
    if (related_apply) {
      return (
        <TouchableOpacity style={{}}
                          onPress={() => {
                            this.props.navigation.navigate('apply_show', {apply_id: related_apply.id})
                          }}>
          {this._label_item([related_apply.name, '点击查看 >'])}
        </TouchableOpacity>
      )
    } else {
      return null
    }
  };

  _audits_info = () => {
    const audits = this.state.data.apply.audits
    if (audits && audits.length > 0) {
      return (
        <View style={styles.apply_base}>
          <Text style={{padding: 15}}>审批情况</Text>
          {audits.map((t, i) => this._audit_item(t, i))}
        </View>
      )
    } else {
      return null
    }
  };

  _executions_info = () => {
    const executions = this.state.data.apply.executions
    if (executions && executions.length > 0) {
      return (
        <View style={styles.apply_base}>
          <Text style={{padding: 15}}>执行人</Text>
          {executions.map((t, i) => this._execution_item(t, i))}
        </View>
      )
    } else {
      return null
    }
  };
  _operations_info = () => {

    const apply = this.state.data.apply,
          executions_user_ids = apply.executions&&apply.executions.map((t)=>t.executer_id)
    //只可能出现一种操作
    if (apply.can_audit) {
      return (
        <View style={{flexDirection: 'row'}}>
          <TouchableOpacity style={[styles.apply_operation, {flex: 1}]} onPress={this._agree_add_executor}>
            <Text style={{color: 'white'}}>通过</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.apply_operation, {backgroundColor: '#f96460', flex: 1}]}
                            onPress={this._open_deny_reason}>
            <Text style={{color: 'white'}}>驳回</Text>
          </TouchableOpacity>
        </View>
      )
    } else if (apply.can_execute) {
      return (
        <TouchableOpacity style={styles.apply_operation} onPress={this.do_confirm_execution}>
          <Text style={{color: 'white'}}>确认已执行</Text>
        </TouchableOpacity>
      )
    } else if (apply.can_add_executor) {
      return (
        <TouchableOpacity style={styles.apply_operation}
                          onPress={()=> this.props.navigation.navigate('select_user',{call_back: this.do_add_execution_users, user_ids: executions_user_ids})}>
          <Text style={{color: 'white'}}>添加执行人</Text>
        </TouchableOpacity>
      )
    } else {
      return null
    }
  };

  _open_deny_reason = ()=>{
    this.props.navigation.navigate('deny_reason',{call_back: this._deny_apply})
  }

  _deny_apply = (remark) => {
    const apply = this.state.data.apply
    UpdateApplyApi({do_action: 'deny',id: apply.id, remark: remark}).then((data)=>{
      if(data.success){
        this.getData()
        Alert.alert('驳回成功！')
      }else{
        Alert.alert(data.msg)
      }
    })
  }

  _agree_add_executor = () => {
    const apply = this.state.data.apply
    UpdateApplyApi({do_action: 'audit',id: apply.id}).then((data)=>{
      if(data.success){
        this.getData()
        if (apply.is_last_auditor) {
          Alert.alert(
            '是否需要添加执行人？',
            '',
            [
              {
                text: '需要', onPress: () => {
                this.props.navigation.navigate('select_user',{call_back: this.do_add_execution_users})}
              },
              {text: '不需要'},
            ],
            {cancelable: false}
          )
        }
      }else{
        Alert.alert(data.msg)
      }
    })



  };

  do_audit = ()=> {

  }

  do_confirm_execution = ()=>{
    const apply = this.state.data.apply
    UpdateApplyApi({do_action: 'confirm_execution',id: apply.id}).then((data)=>{
      this.getData()
      Alert.alert('确认成功！')
    },(data)=>Alert.alert('确认失败！'))
  }

  do_add_execution_users = (ids)=>{
    const apply = this.state.data.apply
    UpdateApplyApi({do_action: 'add_executors',id: apply.id, executors: ids}).then((data)=>{
      this.getData()
      Alert.alert('添加成功！')
    },(data)=>Alert.alert('添加失败！'))

  }

  render() {
    const {loading, data} = this.state;
    if (loading) {
      return <Loading/>
    } else {
      return (
        <View style={{flex: 1}}>
          <ScrollView bounces={false} style={{flex: 1}}>
            {this._base_info()}
            {this._table_info()}
            {this._audits_info()}
            {this._executions_info()}
          </ScrollView>
          <View style={{backgroundColor: 'white'}}>{this._operations_info()}</View>
        </View>
      )
    }

  }
}

export default ApplyShow